<!--
 * @FileDescription: 全局顶部路由进度指示器
 -->
<script setup lang="ts">
import { Event, useEvent } from '@/stores/event';

withDefaults(
  defineProps<{
    colorFrom?: string;
    colorTo?: string;
  }>(),
  {
    colorFrom: '#0076ff',
    colorTo: '#0076ff',
  }
);

const width = ref(0);
const opacity = ref(0);

const { pause, resume, isActive } = useIntervalFn(
  () => {
    if (width.value < 10) width.value = 10;
    else width.value += Math.random();
  },
  100,
  { immediate: false }
);

useEvent(Event.showTopLoader, () => {
  width.value = 0;
  opacity.value = 1;
  resume();
});

useEvent(Event.hideTopLoader, () => {
  if (!isActive.value) return;
  pause();
  width.value = 100;
  opacity.value = 0;
  setTimeout(() => {
    width.value = 0;
  }, 450);
});
</script>

<template>
  <div
    class="progress-bar rounded-r"
    :style="{
      width: `${width}%`,
      opacity: opacity,
      backgroundImage: `linear-gradient(to right, ${colorFrom}, ${colorTo})`,
    }"
  ></div>
</template>

<style scoped>
.progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  height: 3px;
  z-index: 2147483647;
  transition:
    width 300ms ease-out,
    opacity 150ms 150ms ease-in;
}
</style>
